package com.atguigu.day04;

import com.atguigu.utils.ClickEvent;
import com.atguigu.utils.ClickSource;
import org.apache.flink.api.common.state.MapState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

// 每个用户针对每个url访问了多少次
public class Example6 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .addSource(new ClickSource())
                .keyBy(r -> r.username)
                .process(new PV())
                .print();

        env.execute();
    }

    public static class PV extends KeyedProcessFunction<String, ClickEvent, String> {
        // KEY：url
        // VALUE：url的访问次数
        private MapState<String, Integer> mapState;

        private ValueState<Long> timerTs;
        @Override
        public void open(Configuration parameters) throws Exception {
            super.open(parameters);
            mapState = getRuntimeContext().getMapState(
                    new MapStateDescriptor<String, Integer>(
                            "url-pv",
                            Types.STRING, // KEY 的类型
                            Types.INT     // VALUE 的类型
                    )
            );

            timerTs = getRuntimeContext().getState(
                    new ValueStateDescriptor<Long>(
                            "timer",
                            Types.LONG
                    )
            );
        }

        @Override
        public void processElement(ClickEvent value, Context ctx, Collector<String> out) throws Exception {
            if (!mapState.contains(value.url)) {
                // 如果不存在url这个key
                mapState.put(value.url, 1);
            } else {
                // 如果存在url这个key，则访问量加1
                mapState.put(
                        value.url,
                        mapState.get(value.url) + 1
                );
            }

            if (timerTs.value() == null) {
                long tenSecLater = ctx.timerService().currentProcessingTime() + 10 * 1000L;
                ctx.timerService().registerProcessingTimeTimer(tenSecLater);
                timerTs.update(tenSecLater);
            }
        }

        @Override
        public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
            super.onTimer(timestamp, ctx, out);
            StringBuilder result = new StringBuilder();
            result.append(ctx.getCurrentKey() + " {\n");
            for (String key : mapState.keys()) {
                result.append("  ");
                result.append(key + " : " + mapState.get(key) + ";");
                result.append("\n");
            }
            result.append("}\n\n");
            out.collect(result.toString());
            timerTs.clear();
        }
    }
}
